package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xn.app.muying.MuYingApplication;
import com.xn.app.muying.R;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2016/10/19.
 */
public class YunChanSheZhiActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView riqi_tv;
    private TextView jisuan_tv;
    private int id;
    private String pageIntent;
    private String yiyuan;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yuchanqi);
        ImageView back = (ImageView) findViewById(R.id.yuchanshezhi_activity_back);
        Button submit_btn = (Button) findViewById(R.id.yuchanshezhi_activity_btn);
        riqi_tv = (TextView) findViewById(R.id.yuchanshezhi_activity_riqi);
        jisuan_tv = (TextView) findViewById(R.id.yuchanshezhi_activity_jisuan);
        back.setOnClickListener(this);
        riqi_tv.setOnClickListener(this);
        jisuan_tv.setOnClickListener(this);
        submit_btn.setOnClickListener(this);

        yiyuan = getIntent().getExtras().getString("HOSPTIALNAME");
        pageIntent = getIntent().getExtras().getString("PAGE_INTENT");
        id = getIntent().getExtras().getInt("HOSPTIALID");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.yuchanshezhi_activity_back:
                finish();
                break;
            case R.id.yuchanshezhi_activity_riqi:
                Calendar instance = Calendar.getInstance();
                DatePickerDialog pickerDialog = new DatePickerDialog(YunChanSheZhiActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            private StringBuffer stringBuffer;

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {
                                stringBuffer = new StringBuffer("");
                                stringBuffer.append(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " ");
                                riqi_tv.setText("" + stringBuffer);
                            }
                        }, instance.get(Calendar.YEAR),
                        instance.get(Calendar.MONTH),
                        instance.get(Calendar.DAY_OF_MONTH));
                pickerDialog.setTitle("日期");
                pickerDialog.setMessage("请选择预约时间");
                pickerDialog.show();
                break;

            case R.id.yuchanshezhi_activity_jisuan:
                Intent intent = new Intent();
                intent.setClass(YunChanSheZhiActivity.this, YuChanJiSuanActivity.class);
                startActivityForResult(intent, 4);
                break;


            case R.id.yuchanshezhi_activity_btn:
                String mDate = riqi_tv.getText().toString();
                Log.i("text==", mDate);
                if (mDate != null && id != 0) {
                    submit(id, mDate);
                }
                break;

        }
    }

    private void submit(final int id, final String date) {
        MyAlertDialog.ShowDialog(YunChanSheZhiActivity.this, R.layout.dialog_loading);

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    HashMap<String, Object> param = new HashMap<>();
                    param.put("antenatalCareHospitalId", id);
                    param.put("pregnancyStatus", 1);
                    param.put("preDeliveryDate", date);

                    String p = new Gson().toJson(param);
                    Log.i("allen==", p);

                    String tokens = Constants.getStringByName(YunChanSheZhiActivity.this, "yonghu");
                    Type type = new TypeToken<HashMap<String, String>>() {
                    }.getType();
                    HashMap<String, String> token = new Gson().fromJson(tokens, type);
                    Log.i("asdf", "access_token==" + "Bearer " + token.get("access_token"));
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url("http://apitest.beierbaby.com/api/account/pregnancy-info").addHeader("Authorization", "Bearer " + token.get("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();

                    Log.i("code=+=", "code==" + code);
                    Log.i("bodys=+=", bodys);
                    if (code == 204 || code == 200) {


                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (pageIntent != null && yiyuan != null) {
                                    Intent intent = new Intent();
                                    intent.setAction("PREGNANCY_INFO");
                                    intent.putExtra("PAGE_INTENT", pageIntent);
                                    intent.putExtra("HOSPTIALNAME", yiyuan);
                                    sendBroadcast(intent);
                                    finish();
                                } else {
                                    Toast.makeText(YunChanSheZhiActivity.this, "没有拿到PAGE_INTENT的值", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    ToastUtil.showToast(YunChanSheZhiActivity.this, "设置成功");
                    break;
                case 1:
                    ToastUtil.showToast(YunChanSheZhiActivity.this, "设置失败");

                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("shijian", data.getExtras().getString("shijian"));
        String shijian = data.getExtras().getString("shijian");
        String[] strs = shijian.split("T");
        riqi_tv.setText(strs[0].replace("\"", ""));
    }
}
